#!/usr/bin/python
# -*- coding: cp1250 -*-

from pepe.glib import *

zf9 = lambda x: string.zfill(str(x), 9)
# 2683099 -> 002-683-099
x3x = lambda x: "%s-%s-%s" % (zf9(x)[:3], zf9(x)[3:6], zf9(x)[6:9])

n = '\x0D\x0A'

def longest_file_line(f):
    longest_line = 0
    for line in bt.lines(f):
        if len(line) > longest_line:
            longest_line = len(line)
    return longest_line

def add_spaces(data, len_total):
    to_fill = " " * (int(len_total) - len(data))
    return "%s%s" % (data, to_fill)

def main(filemask, text_positioned_or_delimited='d', limit_fname=40):
    '''    Add (append) unique id sufix to each row.

    In Contrast to data_add_unique_id.py (prepend unique ID to each row)
    this will use full source file name (without extension) with length limited to <limit_fname> characters
    and resulting string in the format of uids-xxx-xxx-xxx-<fname> will append to each data line.
    
    Empty rows should not be ignored.
    '''
    print '''\n add (append) unique id sufix'''
    print '''\n note: processed files are expected to be in cp1250'''

    print "\t text_positioned_or_delimited", text_positioned_or_delimited

    for f in sorted(glob.glob(filemask)):
        fname = string.split(f, '.')[0]
        print '    ', timenow(), fname
        
        # limit fname to file name without ext and limit length to 20 or as defined
        if len(fname) > int(limit_fname):
            uid_fname = fname[:int(limit_fname)]
        else:
            uid_fname = fname
        """
        # handling file mask as ... f = aa-dataonly\*.dat
        fname = fw_slash(f)
        # fname = aa-dataonly/*.dat
        fname = string.split(fname, '/')[-1]
        # fname = *.dat
        fname = string.split(fname, '.')[0]
        # fname = *
        # take first 3 characters from fname
        fname = fname[:3]
        """
        lino = 0
        
        if text_positioned_or_delimited in ('p', 'P'): 
            LFL = longest_file_line(f)
            #2011-06-15_1423 vip
            of = open("uisx_%s" % (fname), 'wb')
            #of = open("%s.uisx.out" % (fname), 'w')
        else:
            cd = findcoldelimiter_file(f)
            of = open("uisx_%s" % (fname), 'wb')
            #of = open("%s.uisx.csv" % (fname), 'w')

        for line in bt.lines(f):
            lino += 1
            uid = "%s-%s" % (x3x(lino), uid_fname)
            #uid = "uisx-%s-%s" % (x3x(lino), uid_fname)

            line = re.sub('\x0D\x0A', '', line)
            line = re.sub('\x0D', '', line)
            line = re.sub('\x0A', '', line)

            if text_positioned_or_delimited in ('p', 'P'): 
                line = add_spaces(line, LFL)
                line = "%s%s" % (line, uid) + n
            else:
                line = "%s%s%s" % (line, cd, uid) + n

            of.write(line)
            # search for errors ...
        of.close()
        print '    ', timenow()
    print n

if __name__ == "__main__":
    """
    """
    if  len(sys.argv) == 2:
        main(filemask=sys.argv[1])
    elif  len(sys.argv) == 3:
        main(filemask=sys.argv[1], text_positioned_or_delimited=sys.argv[2])
    elif  len(sys.argv) == 4:
        main(filemask=sys.argv[1], text_positioned_or_delimited=sys.argv[2], limit_fname=sys.argv[3])
    else:
        print """        Error in syntax.

        data_add_unique_id_suffix.py <file-name> <text-positioned-or-delimited> [<limit-fname>]

        file-name (mandatory)
            data filename to be processed
            
        text-positioned-or-delimited (mandatory)
            p - text is positioned
            d - text is delimited (default)
            
        limit-fname (optional) file name used in uisx limited to length
            40 characters (default)
        """